package es.exiquets.daos;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.shards.util.Preconditions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public abstract class BaseDAOeXiquetsImpl<T extends Serializable> implements BaseDAOeXiquets<T> {
	private Class<T> clazz;
	
	EntityManager em;
	
	@Override
	public void setClazz(final Class<T> clazzToSet){
		this.clazz = clazzToSet;
	}
	
	@Transactional(readOnly = true)
	public T findOne(final Integer id){
		Preconditions.checkArgument(id != null);
		return (T) getCurrentSession().getReference(this.clazz, id);
	}
	
	@Transactional(readOnly = true)
	public List<T> findAll(){
		return getCurrentSession().createQuery("from " + this.clazz.getName()).getResultList();
	}
	
	@Transactional(readOnly = false)
	public void save(final T entity){
		Preconditions.checkNotNull(entity);
		getCurrentSession().persist(entity);
	}
	
	@Transactional(readOnly = false)
	public void update(final T entity){
		Preconditions.checkNotNull(entity);
		getCurrentSession().merge(entity);
	}
	
	@Transactional(readOnly = false)
	public void delete(final T entity){
		Preconditions.checkNotNull(entity);
		getCurrentSession().remove(entity);
	}
	
	@Transactional(readOnly = false)
	public void deleteById(final Integer entityId){
		final T entity = findOne(entityId);
		Preconditions.checkState(entity == null);
		delete(entity);
	}
	
	@PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
	
	public final EntityManager getCurrentSession(){
		return this.em;
	}
	
}
